from pcaspy import Driver, SimpleServer
from src.SNMP_proto import SNMP_proto
from os import environ
from public.logger import getLogger
from src.IOC_opr import IOC_opr
from config.config import ioc_port
from src.bos import bos
from public._snmp import ping
# IOC类
# logger = getLogger("WR")
TOTAL_POINTS = 2000


class myDriver(Driver):
    # 初始化函数
    def __init__(self, _IOC_opr):
        print("启动IOC")
        super().__init__()
        self.IOC_opr = _IOC_opr
        self.IOC_opr.get_init_pvname(list(self.pvDB.keys()))
        self.IOC_opr.get_function_list(
            self.getParam, self.setParam, self.updatePVs, self.callbackPV)
        bos(self.IOC_opr)
    # 重构read 函数

    def read(self, reason):
        self.IOC_opr.handle_read(reason)
        return super().read(reason)
        
    # 重构write 函数

    def write(self, reason, value):

        self.IOC_opr.handle_write(reason, value)
        super().write(reason, value)
        # return super().write(reason, value)

    def __del__():
        # 类停止函数
        # 用来安全关闭进程
        pass


def myServer(data_list,data_node):
    host_dict = {}
    index_dict = {}
    name_dict = {}
    environ["EPICS_CAS_SERVER_PORT"] = ioc_port
    prefix = ''
    # 频率
    pvdb1 = {
        'TIMS:WR:Frq_Set': {
            'type': 'float',
            'value': 1,
            'desc': "Frequency set",
            'unit': "Hz"
        },
        'TIMS:WR:Ctrl_Set': {
            'type': 'int',
            'value': 1,
            'desc': "Apply set"
        },
        'TIMS:WR:Trigger_Set': {
            'type': 'enum',
            'enums': ['close', 'ac', 'vme'],
            'value': 0
        },
        'TIMS:WR:Trigger_Set_State': {
            'type': 'int',
            'value': 1,
            'desc': "Trigger callback"

        },
        'TIMS:WR:Init_State': {
            'type': 'int',
            'value': 0,
            'desc': "Trigger callback"

        },
        'TIMS:WR:Check_State': {
            'type': 'int',
            'value': 0,
            'desc': "Trigger callback"

        },
        'TIMS:WR:Wait_State': {
            'type': 'int',
            'value': 1,
            'asyn': True,
            'scan' : 1

        },
        'TIMS:WR:Reset_Bos': {
            'type': 'enum',
            'enums': ["DisReset","Reset"],
            'asyn': True,
            'scan' : 1
        },
        'TIMS:WR:Enable_Bos': {
            'type': 'enum',
            'enums': ["Disable","Enable"],
            'asyn': True,
            'scan' : 0.5,
            'value':1
        },
        'TIMS:WR:HeartBeat_Enable_Bos': {
            'type': 'enum',
            'enums': ["Disable","Enable"],
            'asyn': True,
            'scan' : 1,
            'value':1
        },
        'TIMS:WR:Timestamp_ns': {
                    'type': 'int',
                    'asyn': True,
                    'scan' : 2
        },
        'TIMS:WR:Timestamp_s': {
                    'type': 'int',
                    'asyn': True,
                    'scan' : 2
        },
        'TIMS:WR:Timestamp_UTC': {
                    'type': 'string',
                    'asyn': True,
                    'scan': 2
                    }
    }
    pvdb2 = {}
    pvdb3 = {}
    pvdb4 = {}
    pvdb5 = {}
    pvdb6 = {}
    pvdb7 = {}
    pvdb8 = {}
    pvdb9 = {}
    pvdb10 = {}
    pvdb11 = {}
    pvdb12 = {}
    pvdb13 = {}
    pvdb14 = {}
    pvdb15 = {}
    pvdb16 = {}
    pvdb17 = {}

    for i in data_list:
        if ping(i["host"]):
            for key, value in i["data"].items():
                # 脉宽
                pvdb2['{}_W'.format(key)] = {
                    'type': 'int',
                    'value': 0,
                    'asyn': True,
                    'unit': "us"
                }
                # 延时
                pvdb3['{}_D'.format(key)] = {
                    'type': 'int',
                    'value': 0,
                    'asyn': True,
                    'unit': "us"
                }
                # 使能
                pvdb4['{}_Enable'.format(key)] = {
                    'type': 'int',
                    'value': 0,
                    'asyn': True
                }
                # 波形
                pvdb5['{}_Wave'.format(key)] = {
                    'type': 'int',
                    'count': TOTAL_POINTS,
                    'value': [0] * TOTAL_POINTS,
                    'asyn': True
                }
                # 触发状态
                pvdb6['{}_TriggerStatus'.format(key)] = {
                    'type': 'enum',
                    'enums': ['close', 'ac','vme'],
                    'value': 0,
                    'asyn': True
                }
                # 同步状态
                pvdb7['{}_SyncStatus'.format(key)] = {
                    'type': 'enum',
                    'enums': ['uninitialized', 'syncNsec', 'syncSec', 'syncPhase', 'trackPhase', 'waitOffsetStable','Error'],
                    'value': 0,
                    'asyn': True
                }
                # 系统时间
                pvdb8['{}_SystemTime'.format(key)] = {
                    'type': 'string',
                    'value': "",
                    'asyn': True
                }
                # 系统运行时间
                pvdb9['{}_RunTime'.format(key)] = {
                    'type': 'string',
                    'value': "",
                    'asyn': True
                }
                # 温度
                pvdb10['{}_Temperature'.format(key)] = {
                    'type': 'float',
                    'value': 0.0,
                    'asyn': True,
                    'unit': "Celsius"
                }
                # 新加入的往返延迟
                pvdb11['{}_RTT'.format(key)] = {
                    'type': 'int',
                    'value': 0,
                    'asyn': True,
                    'unit': "ps"
                }
                # 光纤插入情况
                pvdb12['{}_PortLinkStatus'.format(key)] = {
                    'type': 'enum',
                    'enums': ['na', 'down', 'up'],
                    'value': 0,
                    'asyn': True
                }
                # sfp型号
                pvdb13['{}_SfpPn '.format(key)] = {
                    'type': 'string',
                    'value': 0,
                    'asyn': ""
                }
                # sfp tx
                pvdb14['{}_SfpTx'.format(key)] = {
                    'type': 'int',
                    'value': 0,
                    'asyn': True
                }
                # sfp rx
                pvdb15['{}_SfpRx'.format(key)] = {
                    'type': 'int',
                    'value': 0,
                    'asyn': True
                }
                # sfp alpha
                pvdb16['{}_SfpAlpha'.format(key)] = {
                    'type': 'int',
                    'value': 0,
                    'asyn': True
                }
                pvdb17['{}:HeartBeat'.format(key)] = {
                'type': 'enum',
                'enums': ["Wait","Ready"],
                'asyn': True,
                'scan' : 2
                }
                pvdb17['{}:HeartBeat_Ready'.format(key)] = {
                'type': 'enum',
                'enums': ["Wait","Ready"],
                'asyn': True,
                'scan' : 2
                }
                pvdb17['{}:HeartBeat_Enable'.format(key)] = {
                'type': 'enum',
                'enums': ["Disable","Enable"],
                'asyn': True,
                'scan' : 2
                }
                pvdb17['{}:InterLock'.format(key)] = {
                    'type': 'enum',
                    'enums': ["InterLock","Normal"],
                    'asyn': True,
                    'scan' : 2,
                }
                pvdb17['{}:InterLock_L'.format(key)] = {
                    'type': 'enum',
                    'enums': ["InterLock","Normal"],
                    'asyn': True,
                    'scan' : 2,
                }
                pvdb17['{}:Bypass'.format(key)] = {
                    'type': 'enum',
                    'enums': ["0","bypass"],
                    'asyn': True,
                    'scan' : 2
                }
                pvdb17['{}:InterlockTimestamp_UTC'.format(key)] = {
                    'type': 'string',
                    'asyn': True,
                    'scan': 2
                    }
                pvdb17['{}:Timestamp_UTC'.format(key)] = {
                    'type': 'string',
                    'asyn': True,
                    'scan': 1
                    }
                host_dict['{}'.format(key)] = i["host"]
                index_dict['{}'.format(key)] = value
                name_dict['{}'.format(key)] = i["name"]
    for key, value in data_node.items():
        # 脉宽
        if ping(value):
            pvdb2['{}_W'.format(key)] = {
                'type': 'int',
                'value': 0,
                'asyn': True,
                'unit': "us"
            }
            # 延时
            pvdb3['{}_D'.format(key)] = {
                'type': 'int',
                'value': 0,
                'asyn': True,
                'unit': "us"
            }
            # 使能
            pvdb4['{}_Enable'.format(key)] = {
                'type': 'int',
                'value': 0,
                'asyn': True
            }
            # 波形
            pvdb5['{}_Wave'.format(key)] = {
                'type': 'int',
                'count': TOTAL_POINTS,
                'value': [0] * TOTAL_POINTS,
                'asyn': True
            }
            # 触发状态
            pvdb6['{}_TriggerStatus'.format(key)] = {
                'type': 'enum',
                'enums': ['close', 'ac','vme'],
                'value': 0,
                'asyn': True
            }
            # 同步状态
            pvdb7['{}_SyncStatus'.format(key)] = {
                'type': 'enum',
                'enums': ['uninitialized', 'syncNsec', 'syncSec', 'syncPhase', 'trackPhase', 'waitOffsetStable','Error'],
                'value': 0,
                'asyn': True
            }
            # 系统时间
            pvdb8['{}_SystemTime'.format(key)] = {
                'type': 'string',
                'value': "",
                'asyn': True
            }
            # 系统运行时间
            pvdb9['{}_RunTime'.format(key)] = {
                'type': 'string',
                'value': "",
                'asyn': True
            }
            # 温度
            pvdb10['{}_Temperature'.format(key)] = {
                'type': 'float',
                'value': 0.0,
                'asyn': True,
                'unit': "Celsius"
            }
            # 新加入的往返延迟
            pvdb11['{}_RTT'.format(key)] = {
                'type': 'int',
                'value': 0,
                'asyn': True,
                'unit': "ps"
            }
            # 光纤插入情况
            pvdb12['{}_PortLinkStatus'.format(key)] = {
                'type': 'enum',
                'enums': ['na', 'up', 'down'],
                'value': 0,
                'asyn': True
            }
            # sfp型号
            pvdb13['{}_SfpPn '.format(key)] = {
                'type': 'string',
                'value': 0,
                'asyn': ""
            }
            # sfp tx
            pvdb14['{}_SfpTx'.format(key)] = {
                'type': 'int',
                'value': 0,
                'asyn': True
            }
            # sfp rx
            pvdb15['{}_SfpRx'.format(key)] = {
                'type': 'int',
                'value': 0,
                'asyn': True
            }
            # sfp alpha
            pvdb16['{}_SfpAlpha'.format(key)] = {
                'type': 'int',
                'value': 0,
                'asyn': True
            }
            pvdb17['{}:HeartBeat'.format(key)] = {
            'type': 'enum',
            'enums': ["Wait","Ready"],
            'asyn': True,

            }
            pvdb17['{}:HeartBeat_Ready'.format(key)] = {
            'type': 'enum',
            'enums': ["Wait","Ready"],
            'asyn': True,

            }
            pvdb17['{}:HeartBeat_Enable'.format(key)] = {
            'type': 'enum',
            'enums': ["Disable","Enable"],
            'asyn': True,
            }
            pvdb17['{}:InterLock'.format(key)] = {
                'type': 'enum',
                'enums': ["InterLock","Normal"],
                'asyn': True,
            }
            pvdb17['{}:InterLock_L'.format(key)] = {
                'type': 'enum',
                'enums': ["InterLock","Normal"],
                'asyn': True,
            }
            pvdb17['{}:Bypass'.format(key)] = {
                'type': 'enum',
                'enums': ["0","bypass"],
                'asyn': True,
            }
            pvdb17['{}:InterlockTimestamp_UTC'.format(key)] = {
                    'type': 'string',
                    'asyn': True,
                    'scan': 2
                    }
            pvdb17['{}:Timestamp_UTC'.format(key)] = {
                    'type': 'string',
                    'asyn': True,
                    'scan': 1
                    }
            host_dict['{}'.format(key)] = value
            index_dict['{}'.format(key)] = 0
            name_dict['{}'.format(key)] = "Node"
    print("PV 变量已确认")
    server = SimpleServer()
    server.createPV(prefix, pvdb1)
    server.createPV(prefix, pvdb2)
    server.createPV(prefix, pvdb3)
    server.createPV(prefix, pvdb4)
    server.createPV(prefix, pvdb5)
    server.createPV(prefix, pvdb6)
    server.createPV(prefix, pvdb7)
    server.createPV(prefix, pvdb8)
    server.createPV(prefix, pvdb9)
    server.createPV(prefix, pvdb10)
    server.createPV(prefix, pvdb11)
    server.createPV(prefix, pvdb12)
    server.createPV(prefix, pvdb13)
    server.createPV(prefix, pvdb14)
    server.createPV(prefix, pvdb15)
    server.createPV(prefix, pvdb16)
    server.createPV(prefix, pvdb17)
    server.setDebugLevel(level=0)
    _IOC_opr = IOC_opr(data_list=data_list,data_node = data_node,index_dict=index_dict,
                       host_dict=host_dict, name_dict=name_dict)
    driver = myDriver(_IOC_opr)
    while True:
        server.process(0.1)
